package com.sprite.utils.json;

import java.util.HashMap;
import java.util.Map;

public class JsonObject {

    private String prefix = "{";
    private String suffix = "}";

    private Map<String, Object> filedMap = new HashMap<>();

    public void put(String key, Object value) {
        filedMap.put(key, value);
    }

    @SuppressWarnings("unchecked")
    public <T> T get(String key) {
        return (T) filedMap.get(key);
    }

    public void putJsonString(String key, String json) {
        filedMap.put(key, new JsonString(json));
    }

    public String toJson() {
        StringBuilder json = new StringBuilder();
        json.append(prefix);

        boolean isFirst = true;
        for (Map.Entry<String, Object> entry : filedMap.entrySet()) {
            Object value = entry.getValue();
            if (value == null) {
                continue;
            }
            if (!isFirst) {
                json.append(",");
            }
            json.append("\"").append(entry.getKey()).append("\":");

            if (JsonObject.class.isInstance(value)) {
                json.append(value.toString());
            } else if (CharSequence.class.isInstance(value)) {
                json.append("\"").append(value).append("\"");
            } else if (Number.class.isInstance(value)) {
                json.append(value.toString());
            } else {
                json.append(value);
            }

            isFirst = false;
        }

        json.append(suffix);

        return json.toString();
    }
}
